<script setup lang="ts">
import { YkLogin, utils } from 'yklib'
import router from '../router'
import { onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useToolStore } from '../stores/tool'


const { isLogin, currentUsername, currentUserEmail, money, vip, lastLogin, lastTickTime } = storeToRefs(useToolStore())
const host = 'https://sges.yangke.site:5001/'
const loginRef = ref<InstanceType<typeof YkLogin>>()
let settings = {} as any

// 加载设置
const loadSettings = async () => {
  try {
    settings = await window.pywebview.api.read_settings()
    loginRef.value.username = settings.App.username || ''
    loginRef.value.password = settings.App.password || ''
    loginRef.value.rememberAccount = settings.App.rememberAccount || true
  } catch (error) {
    console.log('加载失败，如果未设置settings.yaml文件，可以忽略:', error)
  }
}

const login = async (username: string, password: string) => {
  const user = await utils.login(host, username, String(password))

  if (user && user.isLogin) { // 如果登录成功
    currentUsername.value = user.username!
    currentUserEmail.value = user.email!
    money.value = user.money!
    vip.value = user.vip!
    lastLogin.value = user.lastLogin!
    isLogin.value = user.isLogin! as any
    lastTickTime.value = '' // 如果更换了用户登录，lastTickTime需要清空，以使心跳函数可以重新触发，从而正常扣费
    await router.push('./download')
  }
  if (loginRef.value) { // 点击登录按钮后即保存登录界面的信息
    settings.App.username = loginRef.value.username
    settings.App.password = loginRef.value.password
    settings.App.rememberAccount = loginRef.value.rememberAccount
    await window.pywebview.api.save_settings(settings)
  }
}

const register = async (username: string, password: string, email?: string) => {
  await utils.register(host, username, password, email)
}

const color1 = '#fff'
const color2 = 'coral'
const color3 = 'black'
onMounted(() => {
  // 判断当前用户是否已经登录，如果已经登录，则直接跳转到功能页面
  if (isLogin.value) {
    router.push('./download')
  }
})

window.addEventListener('pywebviewready', async () => {
  console.log('pywebview is ready')
  await loadSettings()
})

</script>

<template>
  <YkLogin ref="loginRef" :loginFn="login" :registerFn="register" :background1="color1" :text-color="color3"
           :background2="color2" login-text2="Stocks同步服务">
  </YkLogin>
</template>

<style scoped>

</style>